#!/usr/bin/env bash
# bash script for GTM
CUR_PATH="$(dirname "${BASH_SOURCE[0]}")"
# shellcheck source=./common.sh
source "${CUR_PATH}/common.sh"

log:info "Starting as global transaction manager (GTM)"

# init and load methods.
# shellcheck source=./initialize_env_dependencies
source "${CUR_PATH}/initialize_env_dependencies"
# shellcheck source=./methods_recovery
source "${CUR_PATH}/methods_recovery"

# validating data directory.
log:info "Creating data directory if does not exist"
mkdir -p "${PGDATA}"

# call to recover if needed.
recover_if_needed || exit $?

log:info "Set data folder permissions 0700"
chmod -R 0700 "${PGDATA}"

# loading current gtm control info.
CONTROL_INFO=""
if [ -f "${PGDATA}/gtm.control" ]; then
  CONTROL_INFO=$(cat "${PGDATA}/gtm.control")
  CONTROL_INFO=${CONTROL_INFO##*( )}
fi

if [ -z "${CONTROL_INFO}" ]; then
  log:info "GTM configuration not found, calling initdb"

  initgtm -D "${PGDATA}" -Z gtm

  # shellcheck source=./initialize_networks
  source "${CUR_PATH}/initialize_networks" || exit $?
  # shellcheck source=./initialize_node_config
  source "${CUR_PATH}/initialize_node_config" || exit $?
else
  log:info "GTM configuration found, init skipped."
  if [ -f "${PGDATA}/gtm.pid" ]; then
    log:warning "GTM process not shut down properly or chart was terminated." \
      "Lock file gtm.pid still exists. Deleting old lock file."
    rm "${PGDATA}/gtm.pid"
  fi

  log:info "Current control state:"
  echo "${CONTROL_INFO}"
  echo
fi

# replication section
# shellcheck source=./initialize_standby_gtm
source "${CUR_PATH}/initialize_standby_gtm" || exit $?

backup_data_state &
log:info "Started gtm recovery process"

# start the GTM
gtm -D "${PGDATA}" -h "${PG_HOST}" -n "${PG_NODE}" -p "${PG_GTM_PORT}" -l /dev/stdout